const app = getApp()
import { children } from '../../utils/utils'
import axios from '../../utils/axios'
import { formatDate } from '../../utils/utils'
var qqmapsdk
import QQMapWX from '../../utils/qqmap-wx-jssdk'
import { Map } from '../../utils/utils'
Page({
	data: {
		notice: [], // 新闻公告
		localShow: false, // 显示附近的地址
		localList: [], // 地址列表
		userLocal: '', // 用户选择的地址
		newsList: {}, // 新闻列表
		talentList: [], // 达人展示
		coachList: [], // 教师展示
		lessonList: [], // 课堂展示
	},
	async onLoad(options) {
		if (wx.getStorageSync('token')) {
			wx.switchTab({
				url: '/pages/user/user',
			})
		}
		this.getHomePageData()
		// // 获取课堂展示
		// 弹出附近的地址picker
		// this.getLocal();
	},
	async onPullDownRefresh() {
		wx.showToast({
			title: '加载中...',
			icon: 'loading',
			duration: 3000,
			mask: false,
		})
		await this.getHomePageData()
		wx.stopPullDownRefresh()
		wx.hideToast()
	},
	async onShow() { },
	onReady: function () { },
	navigationToDetail(e) {
		wx.navigateTo({
			url: '../../components/home/about/about',
			success: res => {
				// console.log("发送数据")
				res.eventChannel.emit('sendData', {
					data: e.currentTarget.dataset.data,
				})
			},
		})
	},
	async getBanner() {
		let bannerRes = await axios({
			url: '/api/shop/home/slide',
			// /api/classroom/indexShow
		})
		console.log('bannerRes', bannerRes)
		this.setData({
			banner: bannerRes.data.content,
		})
	},
	// 图片和通知的点击事件
	handleClick() {
		console.log('handleClick')
		wx.navigateTo({
			url: '../../components/home/news/news',
			success: result => {
				console.log('跳转成功')
			},

			fail: err => console.log('跳转失败', err),
			complete: () => { },
		})
	},
	async navigationTo(e) {
		// 判断登录
		if (app.globalData.userInfo.length === 0) {
			wx.switchTab({
				url: '/pages/user/user',
			})
			return
		}
		let data = e.currentTarget.dataset.data
		switch (data) {
			// tabbar页跳转
			case 'home':
			case 'shop':
			case 'course':
			case 'homeuser':
				wx.switchTab({
					url: `/pages/${data}/${data}`,
				})
				break
			// 展示类
			case 'park':
			case 'team':
			case 'talent':
			case 'showClass':
				wx.navigateTo({
					url: `./aboutUs/aboutUs?showType=${data}`,
				})
				break
			case 'data':
				let childrenRes = await children.getMyChildren()
				if (childrenRes.data.length == 0) {
					wx.showToast({
						title: '\n\n暂无宝宝数据\n\n',
						icon: 'none',
						duration: 1500,
						mask: false,
					})
					return
				}
				let healthRes = await children.getMyChildrenHealthData(
					childrenRes.data[0].id
				) // 默认第一个小孩的健康数据
				// console.log('第一个小孩',childrenRes);
				wx.navigateTo({
					url: '/components/page/childrenData/childrenData',
					success: res => {
						res.eventChannel.emit('sendChildrenData', {
							children: childrenRes.data[0],
							data: healthRes.data.content,
						})
					},
				})
				break
			default:
				console.log('err:page 404')
				break
		}
	},
	async goToDetail(e) {
		let detailData = e.currentTarget.dataset.data
		// if (e.currentTarget.dataset.bannerurl) {
		//   let id = JSON.parse(e.currentTarget.dataset.bannerurl).id;
		//   let res = await axios({
		//     url: '/api/cms/competition',
		//     data: {
		//       id
		//     }
		//   })
		//   detailData = res.data.content[0]
		// };
		wx.navigateTo({
			url: '/components/page/news/news',
			success: res => {
				res.eventChannel.emit('sendNewsData', {
					data: detailData,
				})
			},
		})
	},
	goToClass(e) {
		// let classData = e.currentTarget.dataset.data;
		// console.log('handleclick!', classData);
		// wx.navigateTo({
		//   url: '/pages/user/detail/myClass/classDetail/classDetail',
		//   success: (res) => {
		//     res.eventChannel.emit('classDetail', {
		//       data: classData
		//     })
		//   },
		//   fail: err => console.log(err)
		// });
	},
	// 获取附近的地址
	async getLocal() {
		// 实例化API核心类
		qqmapsdk = new QQMapWX({
			key: '4XUBZ-3GYKP-LLMDP-VHLZ6-N323T-KFBOZ',
		})
		let res = await Map.search({
			text: '幼儿园',
			number: 20,
		})
		let result = []
		for (let i = 0; i < res.data.length; i++)
			result = result.concat(res.data[i].title)
		// log
		console.log('用户选择地址', result)
		this.setData({
			localList: result,
			localShow: true,
		})
	},
	changePickerShow() {
		console.log('hide')
		this.setData({
			localShow: !this.data.localShow,
		})
	},
	onSelect(e) {
		this.setData({
			userLocal: e.detail.value,
		})
	},
	// 提交地址
	subLocal() {
		console.log('拿到选择的地址：', this.data.userLocal)
		this.setData({
			localShow: false,
		})
	},
	noop() { },
	async getHomePageData() {
		this.getBanner()
		// 获取少儿达人
		let talentList = await axios({
			url: '/api/juvenile/talent',
			data: {
				page: 0,
				size: 10,
			},
			header: {
				Authorization: wx.getStorageSync('token'),
			},
		})

		console.log(talentList, '少儿达人')
		// 获取导师介绍
		let coachList = await axios({
			url: '/api/coach/show',
			data: {
				page: 0,
				size: 10,
			},
			header: {
				Authorization: wx.getStorageSync('token'),
			},
		})
		console.log(coachList, '导师介绍')
		// 获取课堂展示
		let lessonList = await axios({
			url: '/api/classroom/indexShow',
			method: 'post',
			data: {},
			header: {
				// Authorization: wx.getStorageSync('token'), /传token返回参数不一样
			},
		})
		console.log('课堂展示', lessonList)
		lessonList.data.forEach(item => {
			if (item.images != null) {
				item.images = item.images.split(',')
			}
		})
		// // 过滤
		lessonList.data = lessonList.data.filter(
			(item, idx) => item.images != null && item.isDel != true && idx < 4
		)
		lessonList.data.forEach(item =>
			item.images.forEach(imgItem =>
				imgItem != null || imgItem != ''
					? (imgItem = imgItem.match(/\S+.(jpg|jpeg|png)/g)[0])
					: false
			)
		)

		console.log(lessonList, '课堂展示')
		// 获取 新闻和赛事 信息
		let articleListRes = await axios({
			url: '/api/cms/article/show',
			data: {
				page: 0,
				size: 10,
			},
			header: {
				Authorization: wx.getStorageSync('token'),
			},
		})
		console.log(articleListRes, '新闻列表')

		let noticeListRes = await axios({
			url: '/api/shop/home/news',
			data: {
				page: 0,
				size: 10,
			},
			header: {
				Authorization: wx.getStorageSync('token'),
			},
		})
		console.log(noticeListRes, '公告列表')

		var newsList = {}
		lessonList.data.forEach(item => {
			item.createTime = formatDate('YY-mm-dd', new Date(item.createTime))
			item.updateTime = formatDate('YY-mm-dd', new Date(item.updateTime))
		})
		articleListRes.data.content.forEach(item => {
			// 格式化时间
			item.createTime = formatDate('YY-mm-dd', new Date(item.createTime))
			item.updateTime = formatDate('YY-mm-dd', new Date(item.updateTime))
			if (item.type == '1') {
				if (!newsList.article)
					newsList.article = {
						title: '',
						list: [],
					}
				newsList.article.title = '活动热点'
				newsList.article.list.push(item)
			} else if (item.type == '2') {
				if (!newsList.competition)
					newsList.competition = {
						title: '',
						list: [],
					}
				newsList.competition.title = '教练风采'
				newsList.competition.list.push(item)
			} else if (item.type == '3') {
				if (!newsList.public)
					newsList.public = {
						title: '',
						list: [],
					}
				newsList.public.title = '足球公益'
				newsList.public.list.push(item)
			} else console.log('文章tab bug!')
		})
		console.log('newsList', newsList)
		//  赋值
		this.setData({
			talentList: talentList.data.content,
			coachList: coachList.data.content,
			lessonList: lessonList.data,
			notice: noticeListRes.data.content,
			newsList,
		})
		return '加载完毕'
	},
})
